// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.butler.service.impl;

import com.liuxinlong.common.AosException;
import com.liuxinlong.common.ExcelData;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.BarStatusEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.butler.dto.CommentDto;
import com.liuxinlong.modules.butler.service.CommentService;
import com.liuxinlong.modules.dao.ButlerTrainDao;
import com.liuxinlong.modules.dao.CommentDao;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.NotificationDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.dao.UserMatterDao;
import com.liuxinlong.modules.entity.ButlerTrain;
import com.liuxinlong.modules.entity.Comment;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.entity.UserMatter;
import com.liuxinlong.push.MessagePushService;
import com.liuxinlong.utils.ExcelUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 评论信息业务接口层实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022-12-06
 */
@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private FileManageDao fileManageDao;

    @Autowired
    private UserMatterDao userMatterDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ButlerTrainDao butlerTrainDao;

    @Autowired
    private NotificationDao notificationDao;

    @Autowired
    private MessagePushService messagePushService;

    @Override
    public List<Map<String, Object>> pageCommentInfo(Map<String, Object> queryParam) {
        List<Comment> commentList = commentDao.pageCommentList(queryParam);
        int startNum = (int) queryParam.get("startNum");
        return completeCommentResult(commentList,startNum);
    }

    @Override
    public int getCommentInfoCount(Map<String, Object> queryParam) {
        return commentDao.getCommentCount(queryParam);
    }

    @Override
    @Transactional
    public void addCommentInfo(Comment comment) {
        ButlerTrain butlerTrain = butlerTrainDao.selectById(comment.getParentId());
        if (ObjectUtils.isEmpty(butlerTrain)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "评论失败，课程信息不存在！");
        }
        int currentSort = 99999;
        String createTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        User current = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (StringUtils.isNotEmpty(comment.getReply())) {
            Comment mainInfo = commentDao.selectById(comment.getReply());
            if (ObjectUtils.isEmpty(mainInfo)) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "回复失败，原评论不存在！");
            }
            comment.setReplyUser(StringUtils.isNotEmpty(comment.getReplyUser()) ? comment.getReplyUser() : mainInfo.getCreateUser());
            currentSort = commentDao.getAllCommentSubCount(comment.getReply(), comment.getParentId()) + 1;
        }
        comment.setCreateUser(current.getId());
        comment.setId(SnowFlake.nextIdStr());
        comment.setStatus(1);
        comment.setCreateTime(createTime);
        comment.setSortNum(currentSort);
        commentDao.insert(comment);
//        Notification notification = new Notification();
//        notification.setId(SnowFlake.nextIdStr());
//        notification.setCreateTime(createTime);
//        notification.setCreateUser(comment.getCreateUser());
//        notification.setSourceId(comment.getParentId());
//        Notification parentNotification = new Notification();
//        if (StringUtils.isNotEmpty(comment.getReply())) {
//            notification.setContent(current.getName() + " 回复了你的评论 ");
//            notification.setDealUser(comment.getReplyUser());
//            notification.setSourceType(2);
//            parentNotification.setId(SnowFlake.nextIdStr());
//            parentNotification.setCreateTime(createTime);
//            parentNotification.setCreateUser(current.getId());
//            parentNotification.setSourceId(comment.getParentId());
//            parentNotification.setContent(current.getName() + " 评论了你的课程 " + butlerTrain.getTitle());
//            parentNotification.setDealUser(butlerTrain.getCreateUser());
//            parentNotification.setSourceType(1);
//        } else {
//            notification.setContent(current.getName() + " 评论了你的课程 " + butlerTrain.getTitle());
//            notification.setDealUser(butlerTrain.getCreateUser());
//            notification.setSourceType(1);
//        }
//        if (!StringUtils.equals(notification.getDealUser(), current.getId())) {
//            notificationDao.insert(notification);
//            User targetUser = userDao.selectById(notification.getDealUser());
//            Map<String, String> contentMap = new HashMap<>();
//            contentMap.put("title", "您有一条新消息待查看");
//            contentMap.put("description", notification.getContent());
//            String content = JSON.toJSONString(contentMap);
//            messagePushService.pushMessage(content, targetUser.getSn());
//        }
//        if (StringUtils.isNotEmpty(parentNotification.getId()) &&
//                !StringUtils.equals(parentNotification.getDealUser(), current.getId()) &&
//                !StringUtils.equals(parentNotification.getDealUser(), notification.getDealUser())) {
//            notificationDao.insert(parentNotification);
//            User cardUser = userDao.selectById(parentNotification.getDealUser());
//            Map<String, String> contentMap = new HashMap<>();
//            contentMap.put("title", "您有一条新消息待查看");
//            contentMap.put("description", parentNotification.getContent());
//            String content = JSON.toJSONString(contentMap);
//            messagePushService.pushMessage(content, cardUser.getSn());
//        }
    }

    @Override
    public List<Map<String, Object>> pageCommentManageList(Map<String, Object> queryParam) {
        List<CommentDto> commentList= commentDao.pageCommentManageList(queryParam);
        int startNum = (int) queryParam.get("startNum");
        return completeCommentMResult(commentList,startNum);
    }

    @Override
    public int getCommentManageCount(Map<String, Object> queryParam) {
        return commentDao.getCommentManageCount(queryParam);
    }

    @Override
    public void toppingComment(String id) {
        Comment comment = commentDao.selectById(id);
        if (ObjectUtils.isEmpty(comment)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "置顶状态修改失败，原评论信息不存在！");
        }
        int targetSort = comment.getSortNum() == 99999 ? 1 : 99999;
        comment.setSortNum(targetSort);
        commentDao.updateById(comment);
    }

    @Override
    public void updateComment(Comment comment) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        Comment oldInfo = commentDao.selectById(comment.getId());
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "更新失败，原评论信息不存在");
        }
        oldInfo.setAttach(comment.getAttach());
        oldInfo.setContent(comment.getContent());
        oldInfo.setUpdateUser(currentUser.getId());
        oldInfo.setUpdateTime(TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS));
        commentDao.updateById(oldInfo);
    }

    @Override
    public void deleteComment(String id) {
        Comment oldInfo = commentDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除失败，原评论不存在！");
        }
        commentDao.updateCommentStatus(id, 3);
        fileManageDao.batchInvalidFile(id);
    }

    @Override
    public void examineComment(String id, int result) {
        Comment comment = commentDao.selectById(id);
        if (ObjectUtils.isEmpty(comment)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "审核失败，评论信息不存在！");
        }
        commentDao.updateCommentStatus(id, result == 1 ? 1 : 2);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        User current = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//        if (result == 1) {
//            BarStatistics barStatistics = new BarStatistics();
//            barStatistics.setId(id);
//            barStatisticsDao.insert(barStatistics);
//            barStatisticsDao.addComments(comment.getCardId());
//            Notification notification = new Notification();
//            notification.setId(SnowFlake.nextIdStr());
//            notification.setCreateTime(currentTime);
//            notification.setCreateUser(barComment.getCreateUser());
//            notification.setSourceId(barComment.getCardId());
//            User userInfo = userDao.selectById(barComment.getCreateUser());
//            if (StringUtils.isNotEmpty(barComment.getReply())) {
//                notification.setContent(userInfo.getName() + " 回复了你的评论 ");
//                notification.setDealUser(barComment.getReplyUser());
//                notification.setSourceType(2);
//            } else {
//                notification.setContent(userInfo.getName() + " 回复了你的发帖 " + barCard.getTitle());
//                notification.setDealUser(barCard.getCreateUser());
//                notification.setSourceType(1);
//            }
//            notificationDao.insert(notification);
//        }
        UserMatter userMatter = userMatterDao.getBySourceId(id);
        if (!ObjectUtils.isEmpty(userMatter) && userMatter.getStatus() == 0) {
            userMatter.setDealUser(current.getId());
            userMatter.setDealTime(currentTime);
            userMatter.setStatus(1);
            userMatterDao.updateById(userMatter);
        }
    }

    /**
     * 数据补全转换
     *
     * @param originList 原始数据列表
     * @param startNum   起始查询数
     * @return 补全数据
     */
    private List<Map<String, Object>> completeCommentResult(List<Comment> originList, int startNum) {
        if (ObjectUtils.isEmpty(originList)) {
            return new ArrayList<>();
        }
        List<Map<String, Object>> resultList = new ArrayList<>(originList.size());
        Map<String,Map<String,String>> userMap = userDao.getUserMap();
        int sort = startNum + 1;
        for (Comment comment : originList) {
            Map<String, Object> item = ObjectUtils.object2Map(comment);
            item.put("sort", sort);
            item.put("userName", userMap.containsKey(comment.getCreateUser()) ? userMap.get(comment.getCreateUser()).get("name") : "");
            Map<String, Object> query = new HashMap<>();
            query.put("parentId", comment.getParentId());
            query.put("commentId", comment.getId());
            query.put("currentUser", comment.getId());
            query.put("startNum", 0);
            query.put("pageSize", 1000);
            List<Comment> subCommentList = commentDao.pageCommentSubList(query);
            List<Map<String, Object>> subList = new ArrayList<>(subCommentList.size());
            if (!ObjectUtils.isEmpty(subCommentList)) {
                for (Comment subComment : subCommentList) {
                    Map<String, Object> subMap = ObjectUtils.object2Map(subComment);
                    subMap.put("userName", userMap.get(subComment.getCreateUser()).get("name"));
                    subMap.put("replyName", userMap.get(subComment.getReplyUser()).get("name"));
                    subList.add(subMap);
                }
            }
            item.put("children", subList);
            resultList.add(item);
            sort++;
        }
        return resultList;
    }

    /**
     * 数据补全转换
     *
     * @param originList 原始数据列表
     * @param startNum   起始查询数
     * @return 补全数据
     */
    private List<Map<String, Object>> completeCommentMResult(List<CommentDto> originList, int startNum) {
        if (ObjectUtils.isEmpty(originList)) {
            return new ArrayList<>();
        }
        List<Map<String, Object>> resultList = new ArrayList<>(originList.size());
        List<String> idList = originList.stream().map(CommentDto::getParentId).collect(Collectors.toList());
        Map<String,Map<String,String>> trainMap = butlerTrainDao.getTrainMap(idList);
        Map<String,Map<String,String>> userMap = userDao.getUserMap();
        int sort = startNum + 1;
        for (CommentDto comment : originList) {
            Map<String, Object> item = ObjectUtils.object2Map(comment);
            item.put("sort", sort);
            item.put("userName", userMap.containsKey(comment.getCreateUser()) ? userMap.get(comment.getCreateUser()).get("name") : "");
//            item.put("children", new ArrayList<>());
            item.put("statusName", BarStatusEnum.getNameByValue(comment.getStatus()));
            item.put("title", trainMap.containsKey(comment.getParentId()) ? trainMap.get(comment.getParentId()).get("title") : "");
            resultList.add(item);
            sort++;
        }
        return resultList;
    }

    @Override
    public void exportComment(String id, HttpServletResponse response) {
        ExcelData data = new ExcelData();
        data.setFileName("评论导出excel.xlsx");
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("startNum", 0);
        queryParam.put("pageSize", 10000);
        List<CommentDto> commentList= commentDao.pageCommentManageList(queryParam);
        Map<String,Map<String,String>> userMap = userDao.getUserMap();
        String[] head = {"序号", "课程信息", "内容", "状态", "创建人", "时间"};
        data.setHead(head);
        String[][] dataList = new String[commentList.size()][head.length];
        int index = 0;
        for (CommentDto item : commentList) {
            dataList[index][0] = String.valueOf(index);
            dataList[index][1] = item.getParentId();
            dataList[index][2] = item.getContent();
            dataList[index][3] = item.getStatus() == 0 ? "待审核" : item.getStatus() == 1? "审核通过" : "其他";
            dataList[index][4] = userMap.containsKey(item.getCreateUser()) ? userMap.get(item.getCreateUser()).get("name") : "";
            dataList[index][5] = item.getCreateTime();

            index++;
        }
        data.setData(Arrays.asList(dataList));
        ExcelUtils.exportExcel(response, data);
    }

}
